package org.apache.ibatis.demo.factory;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * DemoSqlSessionFactory
 *
 * @author zhaohui
 * @date 2019/12/17 11:03
 */
public class DemoSqlSessionFactory {


    private static final String RESOURCE = "org/apache/ibatis/demo/conf/mybatis.xml";

    /**
     * 开启会话
     *
     * @return session
     */
    public SqlSession openSession() {
        return openSession(true);
    }

    /**
     * 开启会话
     *
     * @param autoCommit 是否自动提交事务
     * @return session
     */
    public SqlSession openSession(boolean autoCommit) {
        try {
            return buildSqlSessionFactoryByBuilder().openSession(autoCommit);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过SqlSessionFactoryBuilder构建SqlSessionFactory
     *
     * @return SqlSessionFactory
     */
    public SqlSessionFactory buildSqlSessionFactoryByBuilder() throws Exception {
        // Resources是mybatis 提供的
        InputStream in = Resources.getResourceAsStream(RESOURCE);
        return new SqlSessionFactoryBuilder().build(in);
    }

}
